import React from "react";
import { Button,  Select, Modal, Cascader, Form, Col, Row, Input} from 'antd/lib';
import ContractApply from "@/services/contractapply";
import notification from "@/services/notification";
import {get} from "lodash";
import Uploads from "@/services/uploads";
import Upload from "antd/lib/upload";
import 'antd/dist/antd.less'
import {StarOutlined, UploadOutlined} from '@ant-design/icons';
import WarningOutlined from "@ant-design/icons/WarningOutlined";
import Customer from "@/services/customer";
import Enums from "@/services/enums";
import Attaches from "@/services/attaches";
import moment from "moment";
import DatePicker from "antd/lib/date-picker";
import locale from 'antd/es/date-picker/locale/zh_CN';
import { currentUser } from "@/services/auth";
const { confirm } = Modal;

export default class applyTable extends React.Component {
  state = {
    loading: true,
    id: "0",//
	  userid: currentUser.id,//--操作员ID
	  bill_date: moment(),//--申请日期
	  employeeid: "",//--经办人
	  departmentid: 0,//--经办部门
	  code: "",//----合同编号
	  name: "",//--合同名称
	  type: "",//--合同类别
	  party_aid: "",//--甲方ID
	  party_bid: "1" ,//--乙方
	  party_cid: "1" ,//--其它关联方
    pay_direction: 0 ,//,--收付方向0-fukuan,1-shoukuan
    pricetype:0,//价格类型 0固定价,1单价结算
	  sign_date: moment(),//--合同签订日期
	  start_date: moment(),//--合同开始日期
	  end_date: moment(),//--合同终止日期
	  amount:"0",//--金额
	  amount_words:"",//----合同金额(大写)
	  status: 0,//--状态
	  annex:[],//--附件
	  message: "",//--纪录事项
    customerdata:[],//供应商表HRP
    employeedata:[],//HRP职员表
    departmentdata:[],//HRP部门表
    pay_directiondata:[{id:0,name:"收款"},
      {id:1,name:"付款"},{id:2,name:"非经济"}],
    pricetypedata:[{id:0,name:"总价合同"},
      {id:1,name:"单价合同"},{id:2,name:"费率合同"},{id:3,name:"成本补偿"},{id:4,name:"绩效激励"}],
    contracttypedata:[],
    isCreateApplyEnabled: true,
  };
  // componentDidMount() {
  //   const userId = this.props.userId || currentUser.id;
  // }
  componentWillMount() {
    Enums.items("contract_enum").then(data => {
      this.setState({
        contracttypedata: data,
      });
    });
    let param={
      page: 1,
      pagesize: 10000,
      strcustomercode: '',
      strcustomername: '',
    }
    Customer.getcustomerlist(param).then(data => {
        this.setState({
            customerdata:data.data,
        });
    });
    //  Customer.query(2).then(data => {
    //   this.setState({
    //     customerdata: data,
    //   });
    // });
    //HRP职员表
    let  params={
      code: "",
      name: "",
      userid: currentUser.id,
    }
     Customer.queryemployee(params).then(data => {
      this.setState({
        employeedata: data,
      });
    });
     //HRP部门表
     params={
      code: "",
      name: "",
      userid: currentUser.id,
    }
    Customer.querydepartment(params).then(data => {
      this.setState({
        departmentdata: data,
      });
      this.refreshData(this.props.data);
    });

  }
  componentDidMount() {
    　　this.props.onRef(this);
  }
     // 这种方式十分适合父子组件的互动，通常是父组件需要通过某些状态控制子组件渲染亦或销毁...
componentWillReceiveProps(nextProps) {//componentWillReceiveProps方法中第一个参数代表即将传入的新的Props
    this.refreshData(nextProps.data);
}
 changeNumMoneyToChinese(money) {
  var cnNums = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"]; //汉字的数字
  var cnIntRadice = ["", "拾", "佰", "仟"]; //基本单位
  var cnIntUnits = ["", "万", "亿", "兆"]; //对应整数部分扩展单位
  var cnDecUnits = ["角", "分", "毫", "厘"]; //对应小数部分单位
  var cnInteger = "整"; //整数金额时后面跟的字符
  var cnIntLast = "元"; //整型完以后的单位
  var maxNum = 999999999999999.9999; //最大处理的数字
  var IntegerNum; //金额整数部分
  var DecimalNum; //金额小数部分
  var ChineseStr = ""; //输出的中文金额字符串
  var parts; //分离金额后用的数组，预定义
  if (money === "") {
    return "";
  }
  money = parseFloat(money);
  if (money >= maxNum) {
    alert('超出最大处理数字');
    return "";
  }
  if (money === 0) {
    ChineseStr = cnNums[0] + cnIntLast + cnInteger;
    return ChineseStr;
  }
  money = money.toString(); //转换为字符串
  if (money.indexOf(".") === -1) {
    IntegerNum = money;
    DecimalNum = '';
  } else {
    parts = money.split(".");
    IntegerNum = parts[0];
    DecimalNum = parts[1].substr(0, 4);
  }
  if (parseInt(IntegerNum, 10) > 0) { //获取整型部分转换
    var zeroCount = 0;
    var IntLen = IntegerNum.length;
    for (var i = 0; i < IntLen; i++) {
      var n = IntegerNum.substr(i, 1);
      var p = IntLen - i - 1;
      var q = p / 4;
      var m = p % 4;
      if (n === "0") {
        zeroCount++;
      } else {
        if (zeroCount > 0) {
          ChineseStr += cnNums[0];
        }
        zeroCount = 0; //归零
        ChineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
      }
      if (m === 0 && zeroCount < 4) {
        ChineseStr += cnIntUnits[q];
      }
    }
    ChineseStr += cnIntLast;
    //整型部分处理完毕
  }
  if (DecimalNum !== '') { //小数部分
    var decLen = DecimalNum.length;
    for ( i = 0; i < decLen; i++) {
       n = DecimalNum.substr(i, 1);
      if (n !== '0') {
        ChineseStr += cnNums[Number(n)] + cnDecUnits[i];
      }
    }
  }
  if (ChineseStr === '') {
    ChineseStr += cnNums[0] + cnIntLast + cnInteger;
  } else if (DecimalNum === '') {
    ChineseStr += cnInteger;
  }
  return ChineseStr;

}
  refreshData(data) {
      let departmentid=data.departmentid;
      if(departmentid===0 && this.state.departmentdata.length>0){
        departmentid=currentUser.orgunit_id;
      }
          this.setState({
            id: data.id,//
            userid: data.userid,//--操作员ID
            bill_date: moment(data.bill_date),//--申请日期
            employeeid: data.employeeid,//--经办人
            departmentid: departmentid,//--经办部门
            code: data.code,//----合同编号
            name: data.name,//--合同名称
            type: data.type,//--合同类别
            party_aid: data.party_aid,//--甲方ID
            party_bid: data.party_bid ,//--乙方
            party_cid: data.party_cid ,//--其它关联方
            pay_direction: data.pay_direction ,//,--收付方向0-fukuan,1-shoukuan
            pricetype: data.pricetype,
           sign_date: moment(data.sign_date),//--合同签订日期
           start_date: moment(data.start_date),//--合同开始日期
           end_date: moment(data.end_date),//--合同终止日期
            amount: data.amount,//--金额
            amount_words:data.amount_words,//----合同金额(大写)
            status: data.status,//--状态
            message: data.message,//--纪录事项
            loading: false,
          });
    Attaches.get({sourceid:data.id,type:"contractapply" }).then(data => {
      this.setState({
        annex: data.annex,
      });
    }).catch(error => {
          this.setState({
            annex:[],//--附件
          });
    });
  }
  amountChange =e =>{
    let moneychinese=this.changeNumMoneyToChinese(e.target.value);
          this.setState({
            amount: e.target.value,
            amount_words: moneychinese,
          });
  }
  // displayRender =label =>{
  //   if(label.length>0) {
  //     return label[label.length - 1];
  //   }else{
  //     return label;
  //   }
  // }
  getcode= (params) => {
    if(!this.props.isnew){
      this.setState({
        bill_date: params.bill_date,
        type: params.type,
      });
      return;
    }
    let type="";
    if(params.type.length>0){
      type=params.type[params.type.length-1];
    }
    let item = {
      tblname:  params.tblname,
      bill_date: params.bill_date,
      type: type,
      tblfield: params.tblfield,
    }
    ContractApply.getcode(item).then(data => {
      this.setState({
        bill_date: params.bill_date,
        code: data[0].code,
        type: 0,
      });
    })
      .catch(error => {
      //  notification.error(error.message, error.detailedMessage);
      });
  }
  bill_dateonchange = (value) => {
    let params = {
      tblname: "contractapply",
      bill_date: value,
      type: this.state.type,
      tblfield: "code",
    }
    this.getcode(params)
  };
  cascaderonChange = (value, selectedOptions) => {
    // let mont= moment().format('YYYYMMDD');
    // if(mont>'20200131'){
    //   let mms='ok'
    // }
   let params={
    tblname: "contractapply",
    bill_date: this.state.bill_date,
    type: value,
    tblfield: "code",
  }
  this.getcode(params)
    // this.setState({
    //   type: value,
    // });
  };
  // cascaderonChange =value =>{
  //   let item=value;
  //         this.setState({
  //           contracttypedata: value,
  //         });
  // }
  handleDelete = record => {
    confirm({
      title: '确定删除合同申请单?',
      icon: <WarningOutlined />,
      content: record.name,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        // OrgUnit.delete(record).then(()=>{
        //   notification.success("合同申请单删除成功.");
        //   this.refreshData('',1);
        // }).catch(error => {
        //   notification.error(get(error, "response.data.message", "删除失败."));
        // });
      },
    });
  };

  handleActive = record => {
    const tip = record.is_active ? "确定停用合同申请单?" : "确定启用合同申请单?";
    confirm({
      title: tip,
      icon: <WarningOutlined />,
      content: record.name,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk:() => {

      },
    });
  };
   handledown(file){
     let  filename=file.url;
     let names=file.name;
     if(names.split('.')[1]!==filename.split('.')[1]){
      filename=filename.split('.')[0] +'.'+names.split('.')[1];
     }
     let AjaxUrl = 'api/upload/downloadfile';
     fetch(AjaxUrl ,{
      method: 'POST',
      body: window.JSON.stringify({filename: filename}),
      credentials: 'include',
      headers: new Headers({
        'Content-Type': 'application/json'
      })}).then((response) => {
      response.blob().then(blob => {
        const aLink = document.createElement('a');
        document.body.appendChild(aLink);
        aLink.style.display='none';
        const objectUrl = window.URL.createObjectURL(blob);
        aLink.href = objectUrl;
        aLink.download = file.name;
        aLink.click();
        document.body.removeChild(aLink);
      });
    }).catch((error) => {
      console.log(error);
    });
  };
   getPdfURL(){
        const _this = this;
        const props = {
            name: 'file',
            action: 'api/upload/uploadfile/contractapply/editor/0/0/'+_this.props.id,
            headers: {
                authorization: 'authorization-text',
            },
         //  onChange: this.handleChange,
         onChange(info) {
                let fileList = [...info.fileList];

                // 1. Limit the number of uploaded files
                // Only to show two recent uploaded files, and old ones will be replaced by the new
                // fileList = fileList.slice(-2);
                // 2. Read from response and show file link
            var newd=[];
            fileList.forEach(file => {
                  if (file.response) {
                    // Component will show file.url as link
                    file.url = 'static/file/'+file.response.filename;
                  }
                  let status = _this.state.status;
                  if(file.bytstatus>=0){
                    status=file.bytstatus;
                  }
             // if(file.status==="done") {
                 const b=[{
                          uid: file.uid,
                          name: file.name,
                          status: file.status,
                          bytstatus: status,
                          url: file.url
                  }];
                if (newd.length < 1) {
                  newd = b;
                } else {
                  newd.push.apply(newd, b);
                }
             // }
                });
                _this.setState({ annex:newd });
              },
           onDownload: this.handledown,
           onRemove(infos){
            let uid=infos.uid;
            const id=_this.props.id;
            Uploads.removefile({sourcetype: "contractapply",sourceid:id,uid:uid}).then(data => {
                 if(data.code==="sucess"){
                    notification.success(data.msg);
                 }
                 else{
                  notification.error(data.msg);
                  }
                }).catch(error => {
                  notification.error(get(error, "response.data.message", "删除失败."));
                });
           },
            showUploadList: {
            showDownloadIcon: true,
            downloadIcon: '下载',
            showRemoveIcon: true,
            removeIcon: <StarOutlined onClick={e => console.log(e, 'custom removeIcon event')} />,
          },
        };
        return props;
    };
  // handleStart = () => {
  //   OrgUnit.select(this.props.orgstruct_id, JSON.stringify(this.state.selectedRowKeys)).then(()=>{
  //     notification.success("成功选取合同申请单.");
  //     this.props.selectChange();
  //     this.setState({ selectedRowKeys:[] });
  //   });
  // };
  // onChange = (value, selectedOptions) => {
  //   this.setState({
  //     text: selectedOptions.map(o => o.label).join(', '),
  //   });
  // };
  // showupload = (e) => {
  //       e.preventDefault();
  //       let formData = new FormData(e.target);
  //   Uploads.uploadfile(formData).then(data => {
  //        if(data.code==="sucess"){
  //           notification.success(data.msg);
  //        }
  //        else{
  //         notification.success(data.msg);
  //         }
  //       }).catch(error => {
  //         notification.error(get(error, "response.data.message", "上传失败."));
  //       });
  // };
  // download= () => {
  //    let AjaxUrl = 'api/upload/downloadfile/2020-03-31 09-20-53 的屏幕截图.png'
  //    fetch(AjaxUrl).then(res => res.blob().then(blob => {
  //           let a = document.createElement('a');
  //           let url = window.URL.createObjectURL(blob);
  //           let filename = res.headers.get('Content-Disposition');
  //           if (filename) {
  //               filename = filename.match(/"(.*)"/)[1]; //提取文件名
  //               a.href = url;
  //               a.download = filename; //给下载下来的文件起个名字
  //               a.click();
  //               window.URL.revokeObjectURL(url);
  //               a = null;
  //           }
  //       }));
  // };
  fieldedit(field){
    if(!this.props.isedit){
      return true;
    }
    if(this.props.colcontrol){
      if(this.props.allow_col.indexOf(field)>=0){
        return false;
      }else{
        return true;
      }
    }else{
      return false;
    }
  }
  render() {
    if (this.state.loading) return null;
    let strstatus;
    if(this.state.status===0){
      strstatus="草稿"
    }else if(this.state.status===1)
    {
      strstatus="审核中"
    }else
    {
      strstatus="已审核"
    };
    return(
      <div>
      <Form  layout="horizontal" {...{labelCol: { span: 4 }, wrapperCol: { span: 14 },} }>
         <Row >
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="申请日期" >
            <DatePicker
              locale={locale}
              style={{ width:  400 }}
              value={this.state.bill_date}
               onChange={this.bill_dateonchange}
              placeholder="申请日期"
              disabled ={this.fieldedit("bill_date")}
              autoFocus
            />
            </Form.Item>
          </Col>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5, color:"red" }} label="状态" >
              <Input
                value={strstatus}
                style={{ width:  400 }}
                placeholder="状态"
                disabled="disabled"
              />
						</Form.Item>
				  </Col>
        </Row>
      <Row >
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="经办部门">
              <Select style={{ width:  400 }}
                    showSearch
                    optionFilterProp="children"
                      value={this.state.departmentid} onChange={value => this.setState({departmentid:value})}  
                      disabled ={this.fieldedit("departmentid")}>
              {(this.state.departmentdata || []).map(item => (
                <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
              ))}
              </Select>
            </Form.Item>
          </Col>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="经办人">
              <Select style={{ width:  400 }}
                    showSearch
                    optionFilterProp="children"
                      value={this.state.employeeid} onChange={value => this.setState({employeeid:value})} 
                      disabled ={this.fieldedit("employeeid")}>
              {(this.state.employeedata || []).map(item => (
                <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
              ))}
              </Select>
            </Form.Item>
				  </Col>
        </Row>
        <Row>
        	<Col span={10} >
            <Form.Item style={{ marginBottom: 5 }} label="合同分类">
              <Cascader options={this.state.contracttypedata} expandTrigger="hover" 
               value ={this.state.type} style={{ width:  400 }}
                        onChange={this.cascaderonChange}  
                        disabled ={this.fieldedit("type")}/>
            </Form.Item>
          </Col>
        </Row>
        <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="合同编码" >
              <Input
                value={this.state.code}
                style={{ width:  400 }}
                onChange={e => this.setState({code:e.target.value})}
                placeholder="合同编码"
                disabled ={this.fieldedit("code")}
                autoFocus
              />
            </Form.Item>
          </Col>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="合同名称">
              <Input
                value={this.state.name}
                style={{ width:  400 }}
                onChange={e => this.setState({name:e.target.value})}
               disabled ={this.fieldedit("name")}
                placeholder="合同名称"
              />
						</Form.Item>
				  </Col>
        </Row>
        <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="合同单位">
              <Select style={{ width:  400 }}
                    showSearch
                    optionFilterProp="children"
                      value={this.state.party_aid} onChange={value => this.setState({party_aid:value})} 
                      disabled ={this.fieldedit("party_aid")}>
              {(this.state.customerdata || []).map(item => (
                <Select.Option key={item.id} value={item.id}>{item.strcustomername}</Select.Option>
              ))}
            </Select>
            </Form.Item>
          </Col>
        </Row>
        {/*<Row>*/}
				{/*  <Col span={10}>*/}
        {/*    <Form.Item style={{ marginBottom: 5 }} label="乙方">*/}
        {/*      <Select style={{ width:  600 }}  value={this.state.party_bid} onChange={value => this.setState({party_bid:value})}  disabled ={this.props.isedit}>*/}
        {/*      {this.state.customerdata.map(item => (*/}
        {/*        <Select.Option key={item.id} value={item.id}>{item.strcustomername}</Select.Option>*/}
        {/*      ))}*/}
        {/*    </Select>*/}
        {/*    </Form.Item>*/}
				{/*  </Col>*/}
        {/*</Row>*/}
        {/*<Row>*/}
				{/*  <Col span={10}>*/}
        {/*    <Form.Item style={{ marginBottom: 5 }} label="其它关联方">*/}
        {/*      <Select style={{ width:  600 }}  value={this.state.party_cid} onChange={value => this.setState({party_cid:value})} disabled ={this.props.isedit}>*/}
        {/*      {this.state.customerdata.map(item => (*/}
        {/*        <Select.Option key={item.id} value={item.id}>{item.strcustomername}</Select.Option>*/}
        {/*      ))}*/}
        {/*    </Select>*/}
        {/*    </Form.Item>*/}
				{/*  </Col>*/}
        {/*</Row>*/}
        <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="收付款类型">
              <Select style={{ width:  400 }} value={this.state.pay_direction} onChange={value => this.setState({pay_direction:value})} 
              disabled ={this.fieldedit("pay_direction")}>
              {(this.state.pay_directiondata || []).map(item => (
                <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
              ))}
              </Select>
						</Form.Item>
				  </Col>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="签订日期">
            <DatePicker
              locale={locale}
              style={{ width:  400 }}
              value={this.state.sign_date}
              onChange={value => this.setState({sign_date:value})}
              disabled ={this.fieldedit("sign_date")}
              placeholder="签订日期"
            />
            </Form.Item>
				  </Col>
        </Row>
        <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="价格类型">
              <Select style={{ width:  400 }} value={this.state.pricetype} onChange={value => this.setState({pricetype:value})} 
              disabled ={this.fieldedit("pricetype")}>
              {(this.state.pricetypedata || []).map(item => (
                <Select.Option key={item.id} value={item.id}>{item.name}</Select.Option>
              ))}
              </Select>
						</Form.Item>
				  </Col>
        </Row>
         <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="开始日期">
            <DatePicker
              locale={locale}
              style={{ width:  400 }}
              value={this.state.start_date}
              onChange={value => this.setState({start_date:value})}
              placeholder="开始日期"
              disabled ={this.fieldedit("start_date")}
            />
            </Form.Item>
          </Col>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="终止日期">
            <DatePicker
              locale={locale}
              style={{ width:  400 }}
              value={this.state.end_date}
              onChange={value => this.setState({end_date:value})}
              placeholder="终止日期"
              disabled ={this.fieldedit("end_date")}
            />
            </Form.Item>
				  </Col>
        </Row>
        <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="金额(¥)">
              <Input
                value={this.state.amount}
                style={{ width:  400 }}
                onChange={this.amountChange}
                placeholder="金额(¥)"
                onkeyup="this.value=this.value.replace(/\D/g,'')"
                onafterpaste="this.value=this.value.replace(/\D/g,'')"
                type="number"
                disabled ={this.fieldedit("amount")}
              />
						</Form.Item>
				  </Col>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="金额(大写)">
              <Input
                style={{ width:  400 }}
                value={this.state.amount_words}
                placeholder="金额(大写)"
                disabled ={true}
              />
						</Form.Item>
				  </Col>
        </Row>
        <Row>
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="附件">
              <Upload {...this.getPdfURL()} fileList={this.state.annex} 
              disabled ={this.fieldedit("annex")}>
                <Button>
                  <UploadOutlined /> 上传
                </Button>
              </Upload>
						</Form.Item>
				  </Col>
        </Row>
        <Row >
				  <Col span={10}>
            <Form.Item style={{ marginBottom: 5 }} label="记录事项">
              <textarea
                rows="5" cols="60"
                textAlignVertical="top"
                height="100px"
                value={this.state.message}
                onChange={e => this.setState({message:e.target.value})}
                placeholder="记录事项"
                disabled ={this.fieldedit("message")}
              />
						</Form.Item>
				  </Col>
        </Row>
      </Form>
      </div>
    );
  };
}

